using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Htse.Blue.Models;
using Htse.Blue.Logic.Validation;
using Htse.Blue.Logic;
using System.Data.Linq;

namespace Htse.Blue.Controllers
{
	[HandleError(Order = 0)]
	public class CategoryController : Controller
	{
		private ICategoryService _categoryService;

		public CategoryController()
		{
			_categoryService = new CategoryService(new ModelStateWrapper<Category>(ModelState));
		}

		public CategoryController(ICategoryService categoryService)
		{
			_categoryService = categoryService;
		}

		[Authorize(Roles = SiteConstants.ADMIN_ACCOUNT)]
		public ActionResult List(int? page, string sort)
		{
			var categories = _categoryService.GetAll(page, SiteConstants.PAGE_SIZE, sort);

			if (Request.IsAjaxRequest())
			{
				return PartialView("GridCategoryList", categories);
			}
			else
			{
				return View("List", categories);
			}
		}

		[Authorize(Roles = SiteConstants.ADMIN_ACCOUNT)]
		public ActionResult Create()
		{
			return View("Create", new Category());
		}

		[Authorize(Roles = SiteConstants.ADMIN_ACCOUNT)]
		[ValidateAntiForgeryToken]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Create([Bind(Exclude = "Id")] Category category)
		{
			bool result = _categoryService.Create(category);

			if (result)
			{
				return RedirectToAction("List");
			}
			else
			{
				return View("Create", category);
			}
		}

		[Authorize(Roles = SiteConstants.ADMIN_ACCOUNT)]
		public ActionResult Edit(int id)
		{
			var category = _categoryService.GetById(id);

			if (category == null)
			{
				return View("NotFound");
			}

			return View("Edit", category);
		}

		[Authorize(Roles = SiteConstants.ADMIN_ACCOUNT)]
		[AcceptVerbs(HttpVerbs.Post)]
		[ValidateAntiForgeryToken]
		[HandleError(ExceptionType = typeof(ChangeConflictException), View = "ConcurrencyError")]
		public ActionResult Edit(Category category)
		{
			bool result = _categoryService.Update(category);

			if (result)
			{
				return RedirectToAction("List", "Category");
			}
			else
			{
				return View("Edit", category);
			}
		}

		[Authorize(Roles = SiteConstants.ADMIN_ACCOUNT)]
		[AcceptVerbs(HttpVerbs.Delete)]
		[ActionName("Delete")]
		public ActionResult AjaxDelete(int id)
		{
			var categoryToDelete = _categoryService.GetById(id);

			if (categoryToDelete == null)
			{
				return View("NotFound");
			}

			_categoryService.Delete(categoryToDelete);

			return RedirectToAction("List", "Category");
		}
	}
}
